<template >
  <div class="container">
    <v-t :topHeaderList="topHeaderList"></v-t>
    <el-form
      class="formBox"
      label-width="80px"
      ref="formRef"
      :rules="rules"
      :model="formLabelAlign"
    >
      <el-form-item label="真实姓名" prop="name">
        <el-input v-model="formLabelAlign.name"></el-input>
      </el-form-item>
      <el-form-item label="性别" prop="sex">
        <el-radio-group v-model="formLabelAlign.sex" prop="sex">
          <el-radio label="男"></el-radio>
          <el-radio label="女"></el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item prop="tel" label="手机号">
        <el-input maxlength="11" v-model="formLabelAlign.tel"></el-input>
      </el-form-item>
      <el-form-item label="选择省" prop="pro">
        <el-select v-model="formLabelAlign.pro" placeholder="选择省" @change="getCodePCA('2')">
          <el-option
            v-for="item of codeList.proList"
            :key="item.pro_id"
            :label="item.pro_name"
            :value="item.pro_id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="选择市" prop="city">
        <el-select v-model="formLabelAlign.city" placeholder="选择市" @change="getCodePCA('3')">
          <el-option
            v-for="item of codeList.cityList"
            :key="item.city_id"
            :label="item.city_name"
            :value="item.city_id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="选择县城" prop="area">
        <el-select v-model="formLabelAlign.area" placeholder="选择县城">
          <el-option
            v-for="item of codeList.areaList"
            :key="item.area_id"
            :label="item.area_name"
            :value="item.area_id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="头像" prop="fileUrl">
        <el-upload
          ref="uploadRef"
          action="#"
          list-type="picture-card"
          :auto-upload="false"
          :file-list="fileList"
          :limit="1"
          :before-upload="beforeAvatarUpload"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :on-change="getFileUrl"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog v-model="dialogVisible">
          <img class="imgsBox" :src="dialogImageUrl" alt />
        </el-dialog>
      </el-form-item>
      <el-button type="success" @click="loginFun">提交信息</el-button>
    </el-form>
  </div>
</template>
<script>
import vT from "./topheader.vue";
import axios from "@/axios";
import eventFun from "@/eventFun";
import { useRoute, useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { reactive, ref, onMounted, getCurrentInstance, provide } from "vue";
export default {
  components: { vT },
  // provide: {
  //   zjq: ddd => {
  //     console.log("我是provide", ddd);
  //   }
  // },
  setup(props) {
    let route = useRoute();
    let router = useRouter();
    let { ctx: _this } = getCurrentInstance();
    const validateUsername = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入真实姓名"));
      } else {
        callback();
      }
    };
    let formRef = ref(null);
    let uploadRef = ref(null);
    let dialogImageUrl = ref("");
    let dialogVisible = ref(false);
    let fileList = reactive([]);
    let codeList = reactive({
      proList: [],
      cityList: [],
      areaList: []
    });
    let topHeaderList = [
      { name: "首页", path: "" },
      { name: "用户管理", path: "" },
      { name: "用户信息", path: "/home/userinfo" }
    ];
    const formLabelAlign = reactive({
      name: "",
      tel: "",
      sex: "",
      pro: "",
      city: "",
      area: "",
      fileUrl: ""
    });
    onMounted(() => {
      getCodePCA("1");
      if (route.query.uuid) {
        getUserInfo();
      }
    });

    const getUserInfo = () => {
      axios.get("user/queryId", { uuid: route.query.uuid }).then(async res => {
        let { name, tel, sex, pro, city, area, fileUrl, codeStr } = res.data[0];
        console.log(name, tel, sex, pro, city, area, fileUrl, codeStr);

        if (!codeStr) return;
        formLabelAlign.name = name;
        formLabelAlign.tel = tel;
        formLabelAlign.sex = sex;
        formLabelAlign.pro = pro;
        formLabelAlign.fileUrl = fileUrl;
        await getCodePCA("2");
        formLabelAlign.city = city;
        await getCodePCA("3");
        formLabelAlign.area = area;
        fileUrl
          ? fileList.push({ url: "http://127.0.0.3:3003/" + fileUrl })
          : "";
      });
    };
    const validatePassword = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入手机号"));
      } else if (value.length != 11) {
        callback(new Error("请输入十一位手机号"));
      } else if (
        /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/.test(
          value
        ) != true
      ) {
        callback(new Error("请输入正确手机号"));
      } else {
        callback();
      }
    };
    const validateSex = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请选择性别"));
      } else {
        callback();
      }
    };
    const validatePro = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请选择省"));
      } else {
        callback();
      }
    };
    const validateCity = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请选择市"));
      } else {
        callback();
      }
    };
    const validateArea = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请选择县"));
      } else {
        callback();
      }
    };
    const validateFileUrl = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请选择头像照片"));
      } else {
        callback();
      }
    };
    const rules = {
      name: [{ validator: validateUsername, trigger: "blur" }],
      tel: [{ validator: validatePassword, trigger: "blur" }],
      sex: [{ validator: validateSex, trigger: "blur" }],
      pro: [{ validator: validatePro, trigger: "blur" }],
      city: [{ validator: validateCity, trigger: "blur" }],
      area: [{ validator: validateArea, trigger: "blur" }],
      fileUrl: [{ validator: validateFileUrl, trigger: "blur" }]
    };

    const loginFun = () => {
      formRef.value.validate(valid => {
        if (valid) {
          console.log(formRef.value.validate.toString());
          let uuid;
          if (route.query.uuid) {
            uuid = route.query.uuid;
            uuid == localStorage.getItem("uuid")
              ? eventFun.emit("changeUsernameP", "我是组件A传递的参数字符串")
              : "";
          } else {
            uuid = localStorage.getItem("uuid");
            eventFun.emit("changeUsernameP", "我是组件A传递的参数字符串");
          }
          axios
            .post("user/postInputItem", {
              ...formLabelAlign,
              uuid
            })
            .then(res => {
              res.code === "200" &&
                ElMessage.success({
                  message: res.data.data,
                  type: "success"
                });
              fileList = [];
              resetForm();
              router.push("/home/userlist");
            });
        } else {
          // alert("请填写必填信息");
          return false;
        }
      });
    };
    const handleRemove = (file, fileLists) => {
      fileList = fileLists;
    };
    const resetForm = () => {
      formRef.value.resetFields();
      fileList = [];
      uploadRef.value.clearFiles();
      _this.$forceUpdate();
    };
    const handlePictureCardPreview = file => {
      dialogImageUrl.value = file.url;
      dialogVisible.value = true;
    };
    const getFileUrl = (file, fileLists) => {
      fileList = fileLists;
      let formdata = new FormData();
      formdata.append("myfiles", file.raw);
      axios.post("user/postPto", formdata).then(res => {
        let { data } = res;
        if (res.code === "200") {
          formLabelAlign.fileUrl = data.urlList[0];
        }
      });
    };
    const beforeAvatarUpload = file => {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    };

    const getCodePCA = flag => {
      let code = "";
      if (flag === "2") {
        codeList.areaList = [];
        formLabelAlign.city = "";
        formLabelAlign.area = "";
        code = formLabelAlign.pro;
      } else if (flag === "3") {
        code = formLabelAlign.city;
      } else {
        codeList.cityList = [];
        codeList.areaList = [];
        formLabelAlign.city = "";
        formLabelAlign.area = "";
      }
      axios.get("pcacode/getPCACode", { code }).then(res => {
        if (res.code === "200") {
          if (flag === "1") {
            codeList.proList = res.data.list;
          } else if (flag === "2") {
            codeList.cityList = res.data.list;
          } else {
            codeList.areaList = res.data.list;
          }
        }
      });
    };
    return {
      formLabelAlign,
      rules,
      loginFun,
      formRef,
      dialogImageUrl,
      dialogVisible,
      handleRemove,
      handlePictureCardPreview,
      beforeAvatarUpload,
      getFileUrl,
      codeList,
      getCodePCA,
      fileList,
      uploadRef,
      topHeaderList
    };
  }
};
</script>
<style lang="less" scoped>
.formBox {
  // padding-top: 6%;
  width: 50%;
  padding-left: 3%;
  .imgsBox {
    width: 100%;
    height: 100%;
  }
  /deep/.el-form-item {
    margin-bottom: 16px;
  }
}
</style>